package com.community.common.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.community.common.config.OssProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.util.StopWatch;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class OssUtil {

    @Resource
    private OssProperty ossProperty;

    private static OssProperty OSSPROPERTY;

    private static OSS ossClient;

    @PostConstruct
    public void init() {
        OssUtil.OSSPROPERTY = ossProperty;
    }

    private static OSS getOssClient() throws Exception {
        if (ossClient == null) {
            ossClient = new OSSClientBuilder().build(OSSPROPERTY.endpoint,
                    new String(Base64Utils.decodeFromString(OSSPROPERTY.accessKeyId), StandardCharsets.UTF_8),
                    new String(Base64Utils.decodeFromString(OSSPROPERTY.accessKeySecret), StandardCharsets.UTF_8));
            log.info("初始化OssClient..........");
        }
        return ossClient;
    }

    public static boolean uploadFileByInputStream(InputStream inputStream, String fileName) {
        try {
            OSS ossClient = getOssClient();
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            ossClient.putObject(OSSPROPERTY.bucket, fileName, inputStream);
            stopWatch.stop();
            log.info(" 耗时：{} ms upload to oss finished file:{}", stopWatch.getTotalTimeMillis(), fileName);
            return true;
        } catch (Exception e) {
            log.error("oss upload file:{} uploadFileByInputStream error ", fileName, e);
        }
        return false;
    }

    public static boolean delFile(String fileName) {
        try {
            fileName=fileName.substring(1);
            OSS ossClient = getOssClient();
            ossClient.deleteObject(OSSPROPERTY.bucket, fileName);
            log.info(" delFile finished file:{}", fileName);
            return true;
        } catch (Exception e) {
            log.error("delFile file:{} error ", fileName, e);
        }
        return false;
    }

}
